<?php

namespace App\Admin\Controllers;

use App\Models\Cabinet;
use App\Http\Controllers\Controller;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Callout;
// use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Dcat\Admin\Form;
use App\Models\ProjectUser;
use App\Models\Project;
use App\Models\ProjectPlan;
use App\Models\CabinetAlarmLog;
use Dcat\Admin\Admin;
use Dcat\Admin\Show;
use Illuminate\Http\Request;
use App\Handlers\WeconHandler;
use App\Handlers\AliDeviceHandler;
use App\Admin\Actions\Grid\SyncDeviceCainet;
use Illuminate\Support\Facades\Redis;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Layout\Column;

class CabinetController extends Controller
{
    public function index(Content $content)
    {
        Admin::script(
            <<<JS
    $(".content-header").remove();
    var table = document.getElementById('grid-table');
    table.style.cssText="background-color:#e3e5eb;"
JS            
        );
        $projectList = ProjectUser::where('user_id',Admin::user()->id)->pluck('projectId');
        $boxes = Cabinet::where('pid','0')->whereIn('project_id',$projectList)->get()->toArray();
        $onlineBox = 0;
        foreach ($boxes as $oneBox) {
            $status = WeconHandler::getBoxStatus($oneBox['machine_code']);
            if ($status) {
                $onlineBox++;
            }
        }
        $totalBox = count($boxes);
        $totalAlarm = CabinetAlarmLog::whereIn('project_id',$projectList)->count();
        $undealAlarm = CabinetAlarmLog::whereIn('project_id',$projectList)->where('status', CabinetAlarmLog::STATUS_NO)->count();
        $head = '<div style=\'font-size:14px;height:112px;display: flex;flex-wrap: wrap;justify-content: space-around;width: 100%;text-align:center;margin-top:-10px;margin-bottom:20px;\'>
                    <div style="width:24%;height:112px;background: #FFFFFF;display:flex;">
                        <div style="width:50%;line-height:112px;"><div style=\'height:30%;color:#595959;font-size:19.73px;margin-top:-1.2rem;\'>设备数量</div><div style="font-size:35.7px;color:#66AFF4;">'.$totalBox.'</div></div>
                        <div style="width:50%;"><img style=\'margin-top:14px;margin-bottom:2px;\' src='.url('/icon/num.png').'></div>
                    </div>
                    <div style="width:24%;height:112px;background: #FFFFFF;display:flex;">
                        <div style="width:50%;line-height:112px;"><div style=\'height:30%;color:#595959;font-size:19.73px;margin-top:-1.2rem;\'>设备运行数量</div><div style="font-size:35.7px;color:#FED24A;">'.$onlineBox.'</div></div>
                        <div style="width:50%;"><img style=\'margin-top:14px;margin-bottom:2px;\' src='.url('/icon/inline.png').'></div>
                    </div>
                    <div style="width:24%;height:112px;background: #FFFFFF;display:flex;">
                        <div style="width:50%;line-height:112px;"><div style=\'height:30%;color:#595959;font-size:19.73px;margin-top:-1.2rem;\'>报警总数</div><div style="font-size:35.7px;color:#82D9AB;">'.$totalAlarm.'</div></div>
                        <div style="width:50%;"><img style=\'margin-top:14px;margin-bottom:2px;\' src='.url('/icon/alarm2.png').'></div>
                    </div>
                    <div style="width:24%;height:112px;background: #FFFFFF;display:flex;">
                        <div style="width:50%;line-height:112px;"><div style=\'height:30%;color:#595959;font-size:19.73px;margin-top:-1.2rem;\'>未处理报警数</div><div style="font-size:35.7px;color:#F58080;">'.$undealAlarm.'</div></div>
                        <div style="width:50%;"><img style=\'margin-top:14px;margin-bottom:2px;\' src='.url('/icon/alarm3.png').'></div>
                    </div>
                </div>';
        //各盒子每月报警统计
        $monthAlarmData = $this->getMonthAlarmCount($boxes);

        //各盒子省份分布
        $provincesData = $this->getCabinetProvinces($projectList);

        $row = new Row;
        $row->column(12, function (Column $column) use ($monthAlarmData, $provincesData) {
            $column->row(function(Row $row) use ($monthAlarmData, $provincesData) {
                $row->column(8, view('admin.card.monthAlarm', $monthAlarmData));
                $row->column(4, view('admin.card.cabinetArea', $provincesData));
            });
        });
        return $content
            ->body($head)
            ->body($row)
            ->body($this->grid());
    }

    protected function grid()
    {
        $projectList = ProjectUser::where('user_id',Admin::user()->id)->pluck('projectId');
        $m = Cabinet::where('pid','0')->whereIn('project_id',$projectList);
        return new Grid($m, function (Grid $grid) use ($projectList) {
            $grid->column('name', '名称')->display(function () {
                $url = admin_url('cabinet-children/'.$this->id);
                    return '<a href="'.$url.'" target="_blank">'.$this->name.'</a>';
            });
            $res = Project::whereIn('projectId',$projectList)->pluck('projectname','projectId')->toArray();
            $grid->column('project_id', '所属项目')->using($res);
            $grid->column('machine_code','机器码');
            $grid->column('status','状态')->display(function () {
                $status = WeconHandler::getBoxStatus($this->machine_code);
                if ($status) {
                    return '<span style="color: lightgreen">在线</span>';
                } else {
                    return '<span style="color: red">离线</span>';
                }
            });

            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new SyncDeviceCainet());
            });
        });
    }

    public function update($id){
        return $this->form()->update($id);
    }
    public function store(){
        return $this->form()->store();
    }

    public function create(Content $content){
        return $content
            ->title('新建云盒')
            ->description('创建')
            ->body($this->form());
    }

    public function form(){
        return Form::make(new Cabinet(), function (Form $form) {
            $form->text('name', '名称')->required();
            $list = ProjectUser::where('user_id',Admin::user()->id)->pluck('projectId');
            $res = Project::whereIn('projectId',$list)->pluck('projectname','projectId');
            $form->select('project_id', '所属项目')->options($res)->required()->load('planeJPG', '/planeSelectc');
            // $Plan = ProjectPlan::where('projectId',$form->project_id)->pluck('name','projectId');
            $form->select('planeJPG','位置底图');
            $form->text('machine_code', '机器码')->required();
            $form->text('address', '地址')->default('');
            $form->hidden('box_id')->default(0);

            $form->saving(function (Form $form) {
                $boxId = WeconHandler::getBoxIdByMachineCode($form->machine_code);
                if (empty($boxId)) {
                    return $form->response()->error('无效的维控机器码');
                } else {
                    $form->box_id = $boxId;
                }
            });

            $form->saved(function (Form $form, $result) {
                Cabinet::syncWeikong($form->getKey());
                AliDeviceHandler::registerDevice($form->getKey());
            });

            $form->deleted(function (Form $form, $result) {
                if ($result) {
                    $data = $form->model()->toArray();
                    Cabinet::afterDeletedBox($data[0]['id'], $data[0]['box_id']);
                    AliDeviceHandler::deleteDevice($data[0]['machine_code']);
                }
            });
        });
    }

    public function planeSelectc(Request $request){
        $q = $request->get('q');
        // print_r($q);die;
        return ProjectPlan::where('project_id', $q)->get(['id', DB::raw('name as text')]);
    }

    public function edit($id,Content $content){
        return $content
            ->title('云盒编辑')
            ->description('编辑')
            ->body($this->form()->edit($id));
    }

    public function destroy($id)
    {
        return $this->form()->destroy($id);
    }

    public function show($id){
        return Show::make($id, new Cabinet(), function (Show $show) {
            $show->field('name','名称');
            $list = ProjectUser::where('user_id',Admin::user()->id)->pluck('projectId');
            $res = Project::whereIn('projectId',$list)->pluck('projectname','projectId')->toArray();
            $show->field('project_id','所属项目')->using($res);
            $show->field('machine_code','机器码');
            $show->field('address','地址');
        });
    }

    protected function getMonthAlarmCount($boxes){
        $series = [];
        $head[] = 'box';
        foreach ($boxes as $oneBox) {
            $head[] = $oneBox['name'];
            array_push($series, ['type' => 'bar']);
        }
        $head = json_encode($head);
        $series = json_encode($series);
        $data['series'] = $series;

        $d[] = $head;

        $firstMonth = date("Y-m", strtotime("-11 months"));
        for ($i=0; $i < 12; $i++) { 
            $m = date("Y-m", strtotime("$firstMonth +$i months"));
            $firstDay = date('Y-m-01', strtotime($m));
            $start = date('Y-m-01 00:00:00', strtotime($m));
            if (date("Y-m") == $m) {
                $end = date("Y-m-d H:i:s");
            } else {
                $end = date('Y-m-d 23:59:59', strtotime("$firstDay +1 month -1 day"));
            }
            
            $oneD = [];
            $oneD[] = $m;
            foreach ($boxes as $oneBox) {
                // $oneD[] = CabinetAlarmLog::where('cabinet_pid', $oneBox['id'])->count();
                $oneD[] = rand(0,100);
            }
            array_push($d, json_encode($oneD));

        }
        $data['data'] = $d;
        return $data;
    }

    protected function getCabinetProvinces($projectList){
        $urlPrefix = 'https://restapi.amap.com/v3/geocode/regeo?output=json&location=';
        $urlSuffix = '&key=efc9084469fb60d4aaef0dfe90c7bdf5&extensions=base';
        $provinces = [];
        $projects = Project::select(['projectId','projectname', 'lat', 'lng'])->whereIn('projectId', $projectList)->get()->toArray();
        foreach ($projects as $one) {
            if (intval($one['lat']) && intval($one['lng'])) {
                $url = $urlPrefix.$one['lng'].','.$one['lat'].$urlSuffix;
                $rr = Request_curl($url, false, 0, 0);
                $r = json_decode($rr, true);
                if ($r['status'] && $r['regeocode']['addressComponent']['province']) {
                    $oneP = $r['regeocode']['addressComponent']['province'];
                    array_push($provinces, $oneP);
                }
            }
        }
        $tmpProvince = array_count_values($provinces);
        $provinceData = [];
        foreach ($tmpProvince as $pname => $pnum) {
            $tmpOne['value'] = $pnum;
            $tmpOne['name'] = $pname;
            array_push($provinceData, $tmpOne);
        }
        $data['provinceNum'] = count($tmpProvince);
        $data['provinceData'] = json_encode($provinceData);
        return $data;
    }
}